package com.jcf.springboot.controller.business;

import com.jcf.springboot.entity.business.ChatMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;
import java.time.LocalDateTime;

/**
 * @author Jim
 * @Description 可以跟谁聊天
 * @createTime 2022年05月26日
 */
@Controller
public class ChatController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    private final SimpMessagingTemplate messagingTemplate;


    public ChatController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/chat")
    @SendTo("/queue/chat")
    public void handleMsg(ChatMsg chatMsg, Principal principal) {

        chatMsg.setDate(LocalDateTime.now());

        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(), "/queue/chat", chatMsg);
        System.out.println("-------------"+Thread.currentThread().getName());

    }

    @MessageMapping("/aaa")
    @SendTo("/topic/messages") // 广播到所有订阅者
    public String handleMessage(String message) {
        System.out.println("ws-----------------------------------------");
        simpMessagingTemplate.convertAndSend( "/topic/messages", "66");

        return "服务器收到消息: " + message;
    }
}